package com.atguigu.test05.test06;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author haoranlu
 * @project IntelliJ IDEA
 */
public class JDBCToolsV2 {
    private static DataSource ds;
    private static ThreadLocal<Connection> th ;
    static {
        try {
            Properties pro = new Properties();
            pro.load(JDBCToolsV2.class.getClassLoader().getResourceAsStream("druid.properties"));
            ds = DruidDataSourceFactory.createDataSource(pro);
            th= new ThreadLocal<Connection>();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public static Connection getConnection() throws Exception{
        //获取当前线程中的共享的连接对象
        Connection conn = th.get();
        //当前线程没有拿过连接，第一俄国获取链接
        if (conn == null){
            conn=ds.getConnection();
            th.set(conn);
        }
        return conn;
    }
    /**
     * 把编译时异常转为运行时异常
     */
    public static void free(Connection conn){
        try {
            if (conn != null){
                conn.close();
            }
        }catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    public static int update(String sql,Object... args) throws Exception {
        Connection conn = getConnection();
        PreparedStatement pst = conn.prepareStatement(sql);
        if (args!=null && args.length>0){
            for (int i = 0; i < args.length; i++) {
                pst.setObject(i+1,args[i]);
            }
        }
        int len = pst.executeUpdate();
        pst.close();
        return len;

    }
}
